import pages from "../../pages";
import { wxLogin, Login } from "../../api/login";

Page({
  data: {
    dataAccountFrom: {
      account: "",
      password: ""
    },
    userData: {
      token: ""
    },
    accountError: '',
    passwordError: '',
    loading: false
  },

  onChange(e) {
    const { sign } = e.currentTarget.dataset;
    this.setData({
      [`dataAccountFrom.${sign}`]: e.detail
    });
  },

  // 跳转注册
  jumpRegister() {
    wx.navigateTo({
      url: pages.Register,
    });
  },

  // 账号登录
  accountLogin() {
    const { account, password } = this.data.dataAccountFrom;

    if (!account) {
      this.setData({ accountError: '请输入账号' });
      return;
    } else {
      this.setData({ accountError: '' });
    }

    if (!password) {
      this.setData({ passwordError: '请输入密码' });
      return;
    } else {
      this.setData({ passwordError: '' });
    }

    this.setData({ loading: true });

    Login(this.data.dataAccountFrom).then((info) => {
      this.setData({ loading: false });

      if (info.code === 1) {
        this.setData({
          userData: info
        });
        wx.setStorageSync('userInfo', this.data.userData);

        wx.switchTab({
          url: pages.Home,
        });
      } else {
        wx.showToast({
          title: '登录失败',
          icon: 'none',
          duration: 2000
        });
      }
    }).catch(() => {
      this.setData({ loading: false });
      wx.showToast({
        title: '网络错误',
        icon: 'none',
        duration: 2000
      });
    });
  },

  // 微信登录
  login() {
    wx.getUserProfile({
      desc: "登录",
      success: (res) => {
        this.setData({
          userData: res.userInfo
        });
        wx.login({
          success: (row) => {
            wxLogin({
              code: row.code,
              avatarUrl: res.userInfo.avatarUrl,
              nickName: res.userInfo.nickName
            }).then((info) => {
              if (info.code === 0) {
                wx.showToast({
                  title: '登录成功',
                  icon: 'success',
                  duration: 2000
                });
                this.setData({
                  "userData.token": info.token
                });
                wx.setStorageSync('userInfo', this.data.userData);
                wx.switchTab({
                  url: pages.Home
                });
              } else {
                wx.showToast({
                  title: '登录失败',
                  icon: 'none',
                  duration: 2000
                });
              }
            });
          }
        });
      }
    });
  },

  onLoad(options) {},

  onReady() {},

  onShow() {},

  onHide() {},

  onUnload() {},

  onPullDownRefresh() {},

  onReachBottom() {},

  onShareAppMessage() {}
});
